package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanwei.core.entity.bo.WxUserDetail;
import com.xuanwei.core.entity.vo.UserListVo;
import com.xuanwei.core.service.IXwUserService;
import com.xuanwei.core.util.JwtTokenUtil;
import com.xuanwei.dao.entity.XwUser;
import com.xuanwei.dao.mapper.XwUserMapper;
import com.xuanwei.xwcommon.consts.CacheName;
import com.xuanwei.xwcommon.util.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-07-08
 */
@Service
public class XwUserServiceImpl extends ServiceImpl<XwUserMapper, XwUser> implements IXwUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String saveUser(XwUser user, String ip, String address) {
        //查询是否已经有该用户
        XwUser xwUser = baseMapper.selectOne(new QueryWrapper<XwUser>().select("id").eq("mini_app_openid", user.getMiniAppOpenid()));
        //没有新增
        if (xwUser == null) {
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setRegistryIp(ip);
            user.setRegistryAddress(address);
            save(user);
        } else {
            //修改
            xwUser.setUpdateTime(LocalDateTime.now());
            xwUser.setAvatarUrl(user.getAvatarUrl());
            xwUser.setCity(user.getCity());
            xwUser.setCountry(user.getCountry());
            xwUser.setProvince(user.getProvince());
            xwUser.setGender(user.getGender());
            xwUser.setNickname(user.getNickname());
            xwUser.setRegistryIp(ip);
            xwUser.setRegistryAddress(address);
            updateById(xwUser);
        }
        Integer userId = xwUser == null ? user.getId() : xwUser.getId();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userId, userId);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        user.setId(userId);
        UserDetails userDetails = new WxUserDetail(user);
        String token = tokenUtil.generateToken(userDetails);
        redisTemplate.opsForValue().set(CacheName.USER_TOKEN + user.getId(), token, 7, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Page<UserListVo> page(String nickname, String phone, Page<XwUser> page) {

        QueryWrapper<XwUser> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(nickname)) {
            wrapper.like("nickname", nickname);
        }
        if (StringUtils.isNotBlank(phone)) {
            wrapper.like("cellphone", phone);
        }
        wrapper.orderByDesc("create_time");

        page(page, wrapper);
        Page<UserListVo> pageDate = new Page<>(page.getCurrent(), page.getSize());
        pageDate.setTotal(page.getTotal());
        page.setPages(page.getPages());
        List<UserListVo> userListVos = BeanUtil.copyList(page.getRecords(), UserListVo.class);
        pageDate.setRecords(userListVos);
        return pageDate;
    }
}
